/* eslint-disable no-shadow */
/**
 *  领英
 */
import React from 'react';
import { Form, Input, Select, Button, message, Card, Icon, Alert, Spin } from 'antd';
import { BottomAction } from '@/components';
import { useRequest } from '@/hooks';
import useChannelDict from './useChannelDict';
import DropDownCascader from '../../Setting/containers/DropDownCascader';
import { getCategoryTree } from '../../Setting/service';
import useRecruitOutwardsChannelDetail from './useRecruitOutwardsChannelDetail';
import useRecruitOutwardsChannelUpdate from './useRecruitOutwardsChannelUpdate';

const { Option } = Select;
const channelCode = 'linkedin';

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 9 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
    }
};
const filterTree = tree =>
    tree.map(({ children, positionCategoryCode, positionCategoryName, ...props }) => ({
        children: children && children.length > 0 ? filterTree(children) : '',
        label: positionCategoryName,
        value: positionCategoryCode,
        ...props
    }));
const flat = (tree, parent) =>
    tree.reduce((pre, curr) => {
        const { children, label, value } = curr;
        const item = { label, value, parent };
        let next = [item];
        if (children && children.length) {
            next = [...next, ...flat(children, item)];
        }
        return [...pre, ...next];
    }, []);

function LinkedinForm({ form, outwardId, onSuccess, onError }) {
    const { getFieldDecorator, getFieldsValue, getFieldValue } = form;
    const {
        positionKeyword,
        projectInfo,
        positionIndustry,
        positionJobNature,
        positionSeniorityLevel,
        loading: dictLoading
    } = useChannelDict(channelCode, [
        'positionKeyword',
        'projectInfo',
        'positionIndustry',
        'positionJobNature',
        'positionSeniorityLevel'
    ]);
    // Job function
    const { data: categoryTree, loading: categoryLoading } = useRequest(() => getCategoryTree(channelCode), {
        refreshDeps: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return filterTree(resData || []);
                }
                message.error(msg);
            }
            return null;
        }
    });

    const [runSubmit, submitLoading] = useRecruitOutwardsChannelUpdate(onSuccess, onError);
    const [data, loading] = useRecruitOutwardsChannelDetail(outwardId, channelCode);

    // 初始化
    React.useEffect(() => {
        if (!data) {
            return;
        }
        const channelRecruitInfo = JSON.parse(data?.channelRecruitInfo || null) || { title: undefined };
        const { jobFunctions, employmentStatus, experienceLevel, skills, project_name } = channelRecruitInfo;

        const extend = {
            jobFunctions: jobFunctions ? jobFunctions.map(item => item?.type) : [],
            employmentStatus: employmentStatus?.type,
            experienceLevel: experienceLevel?.type,
            skills: skills?.includedSkills || [],
            project_name: project_name ? [project_name] : []
        };
        const values = { ...channelRecruitInfo, ...extend };
        const formValues = getFieldsValue();
        const exists = key => Object.keys(formValues).indexOf(key) !== -1;
        const nextValues = Object.keys(values).reduce((pre, curr) => {
            if (exists(curr)) {
                return { ...pre, [curr]: values[curr] };
            }
            return { ...pre };
        }, {});
        form.setFieldsValue(nextValues);
    }, [data, categoryTree]);
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFieldsAndScroll((err, values) => {
            if (err) {
                return;
            }
            const findLabel = (dict, val, options = { value: 'selectValue', label: 'selectName' }) => {
                const { value, label } = options;
                if (!dict || !dict.length || !val) {
                    return undefined;
                }
                return dict.find(item => item[value] === val)?.[label];
            };
            const sourceData = JSON.parse(data?.channelRecruitInfo || null) || {}; // shit,将后端返回的未展示在界面上的数据原封不动传至后台
            const { jobFunctions, employmentStatus, experienceLevel, skills, project_name, industries } = values;
            const flatArr = flat(categoryTree);
            const extend = {
                jobFunctions: jobFunctions.map(value => ({
                    type: value,
                    displayName: findLabel(flatArr, value, { value: 'value', label: 'label' })
                })),
                employmentStatus: {
                    type: employmentStatus,
                    displayName: findLabel(positionJobNature, employmentStatus)
                },
                experienceLevel: {
                    type: experienceLevel,
                    displayName: findLabel(positionSeniorityLevel, experienceLevel)
                },
                // shit
                skills: {
                    prefillType: 'INFERRED',
                    skillVersion: 'V5_2',
                    includedSkills: skills,
                    includedSkillsName: skills.map(value => findLabel(positionKeyword, value)),
                    includedSkillsResolutionResults: skills.reduce((pre, value) => {
                        if (!value) {
                            return pre;
                        }
                        return {
                            ...pre,
                            [value]: JSON.stringify({
                                entityUrn: value,
                                skillName: findLabel(positionKeyword, value)
                            })
                        };
                    }, {})
                },
                project_name: project_name?.[0],
                industryNames: industries.map(value => findLabel(positionIndustry, value))
            };
            runSubmit(outwardId, channelCode, JSON.stringify({ ...sourceData, ...values, ...extend }));
        });
    };
    // 标准的
    const renderOptions = dict => {
        if (!dict || !dict.length) {
            return null;
        }
        return dict.map(item => (
            <Option value={item.selectValue} key={item.selectValue}>
                {item.selectName}
            </Option>
        ));
    };

    const renderWarnIcon = style => <Icon style={style || {}} type="warning" theme="twoTone" twoToneColor="#faad14" />;
    const renderWarnLabel = (text, required = true) => (
        <div style={{ position: 'relative', display: 'inline-block', overflowX: 'visible' }}>
            {renderWarnIcon({
                position: 'absolute',
                top: 14,
                left: required ? -30 : -18,
                fontSize: '12px'
            })}

            {text}
        </div>
    );
    return (
        <Card
            bordered={false}
            title={<div style={{ margin: '10px 0' }}>渠道发布信息</div>}
            loading={loading || dictLoading}
            extra={data?.channelLogoUrl && <img height="44" src={data?.channelLogoUrl || ''} alt="BOSS直聘" />}
        >
            <BottomAction>
                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                    提交
                </Button>
            </BottomAction>
            <Alert
                style={{ marginBottom: 24 }}
                message={
                    <div>
                        注：加&nbsp;
                        {renderWarnIcon()}
                        &nbsp;内容在确认发布后，将无法修改
                    </div>
                }
                type="warning"
            />
            <Form {...formItemLayout} className="ant-advanced-search-form">
                <Form.Item label={renderWarnLabel('Job title')}>
                    {getFieldDecorator('title', {
                        initialValue: undefined,
                        rules: [
                            { required: true, message: 'Job Title cannot be empty' },
                            {
                                validator: (rule, value, callback) => {
                                    if (value?.length > 25) {
                                        callback('The length of Job Title cannot exceed 25');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input disabled={data?.hasRelease} placeholder="请输入职位名称" maxLength={25} />)}
                </Form.Item>

                <Form.Item label="Job function">
                    <Spin spinning={categoryLoading}>
                        {getFieldDecorator('jobFunctions', {
                            initialValue: undefined,
                            rules: [{ required: true, message: 'Job Function cannot be empty' }]
                        })(
                            <DropDownCascader
                                onChange={() => {}}
                                options={categoryTree || []}
                                placeholder="Select Job Function"
                                maxCount={3}
                                changeOnLastLevel={false}
                            />
                        )}
                    </Spin>
                </Form.Item>
                <Form.Item label="Company industry">
                    {getFieldDecorator('industries', {
                        initialValue: undefined,
                        rules: [
                            {
                                required: true,
                                message: 'Company Industry cannot be empty'
                            },
                            {
                                validator: (rule, value, callback) => {
                                    if (value?.length > 3) {
                                        callback('The count of Company Industry cannot exceed 3');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <Select
                            mode="multiple"
                            showArrow
                            showSearch
                            allowClear
                            style={{ width: '100%' }}
                            placeholder="Select Company Industry"
                            optionFilterProp="children"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                        >
                            {renderOptions(positionIndustry)}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="Employment type">
                    {getFieldDecorator('employmentStatus', {
                        initialValue: undefined,
                        rules: [
                            {
                                required: true,
                                message: 'Employment Type cannot be empty'
                            }
                        ]
                    })(
                        <Select
                            showArrow
                            showSearch
                            allowClear
                            style={{ width: '100%' }}
                            placeholder="Select Employment Type"
                            optionFilterProp="children"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                        >
                            {renderOptions(positionJobNature)}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="Seniority level">
                    {getFieldDecorator('experienceLevel', {
                        initialValue: undefined,
                        rules: [
                            {
                                required: true,
                                message: 'Seniority Level cannot be empty'
                            }
                        ]
                    })(
                        <Select
                            showArrow
                            showSearch
                            allowClear
                            style={{ width: '100%' }}
                            placeholder="Select Seniority Level"
                            optionFilterProp="children"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                        >
                            {renderOptions(positionSeniorityLevel)}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="Receive notification email">
                    {getFieldDecorator('contactEmail')(<Input disabled />)}
                </Form.Item>
                <Form.Item label="Target your job post">
                    {getFieldDecorator('skills', {
                        initialValue: undefined,
                        rules: [
                            {
                                required: true,
                                message: 'Job Post cannot be empty'
                            }
                        ]
                    })(
                        <Select
                            mode="multiple"
                            showArrow
                            showSearch
                            allowClear
                            style={{ width: '100%' }}
                            placeholder="Select Job Post"
                            optionFilterProp="children"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                        >
                            {positionKeyword?.map(item => (
                                <Option
                                    value={item.selectValue}
                                    key={item.selectValue}
                                    disabled={
                                        getFieldValue('skills')?.length >= 10 &&
                                        !getFieldValue('skills')?.includes(item.selectValue)
                                    }
                                >
                                    {item.selectName}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>

                <Form.Item label={renderWarnLabel('Add to a project')}>
                    {getFieldDecorator('project_name', {
                        initialValue: undefined,
                        rules: [
                            {
                                required: true,
                                message: 'Project cannot be empty'
                            },
                            {
                                validator(rule, value, callback) {
                                    const reg = new RegExp('[\u4E00-\u9FFF]');
                                    if (value?.join && reg.test(value.join(''))) {
                                        callback('Project cannot enter Chinese');
                                        return;
                                    }
                                    if (value?.length > 1) {
                                        callback('The count of Project cannot exceed 1');
                                        return;
                                    }
                                    if (value?.[0]?.length > 60) {
                                        callback('The length of Project cannot exceed 60');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <Select
                            showArrow
                            showSearch
                            allowClear
                            mode="tags"
                            style={{ width: '100%' }}
                            placeholder="Select or input a Project "
                            optionFilterProp="children"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                        >
                            {projectInfo?.map(item => (
                                <Option
                                    value={item.selectValue}
                                    key={item.selectValue}
                                    disabled={
                                        form.getFieldValue('project_name')?.length >= 1 &&
                                        !form.getFieldValue('project_name')?.includes(item.selectValue)
                                    }
                                >
                                    {item.selectName}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>

                <Form.Item label="Job description">
                    {getFieldDecorator('description', {
                        initialValue: undefined,
                        rules: [
                            { required: true, message: 'Job description cannot be empty' },
                            {
                                validator: (rule, value, callback) => {
                                    if (value?.length > 10000) {
                                        callback('The length of Job description cannot exceed 10000');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input.TextArea rows={24} maxLength={10000} placeholder="Job description" />)}
                </Form.Item>
            </Form>
        </Card>
    );
}

export default Form.create({})(LinkedinForm);
